package vip.manda.framework.bean;

import cn.hutool.core.annotation.AnnotationUtil;
import cn.hutool.core.util.ReflectUtil;
import vip.manda.framework.core.Function;
import vip.manda.framework.log.Log;
import vip.manda.framework.log.LogFactory;

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author hongda.li 2022-04-11 10:20
 */
@Function(order = Function.Common.BEAN_FUNCTION)
public class BeanFunction implements Function.FunctionMethod {

    private static final Log log = LogFactory.getLog();

    public BeanFunction() {
        log.func("execute function[{}]", BeanFunction.class.getName());
    }

    @Override
    public void doFunction(Set<Class<?>> classes) {
        BeanContainer container = BeanFactory.getContainer();
        List<Class<?>> singletons = classes.stream()
                .filter(clazz -> AnnotationUtil.hasAnnotation(clazz, Singleton.class))
                .collect(Collectors.toList());
        singletons.forEach(container::setBean);
        singletons.forEach(clazz
                -> Arrays.asList(ReflectUtil.getMethods(clazz, method
                -> AnnotationUtil.hasAnnotation(method, Singleton.class))).forEach(method
                -> container.setBean(ReflectUtil.invoke(container.getBean(clazz), method))));
        container.getBeans().forEach(Assembler::new);
    }
}
